package com.code.service.impl;

import com.code.service.Sms5CService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 验证码业务聚合服务层
 *
 * @author tangyifei
 */
@Slf4j
@Service
public class Sms5CServiceImpl implements Sms5CService {

    private static AtomicInteger count = new AtomicInteger(0);

    private final String url = "http://hk.5c.com.cn/api/send/index.php?username=13632735345&password_md5=1beecf22cce3afcaf55bd41e1f366af5&apikey=04329be860caa9687d801bacb238cce3&encode=UTF-8";

    @Value("${sms.prefix}")
    private String prefix;

    @Autowired
    private RestTemplate restTemplate;

    @Async
    @Override
    public void sendSms(String phone, String context) throws UnsupportedEncodingException {
        if (count.get() >= 5) {
            log.info("请求用户过多，请稍后在试！");
        } else {
            count.incrementAndGet();
            context = prefix + context;

            context = URLEncoder.encode(context, "UTF-8");

            String url = this.url + "&mobile=" + phone + "&content=" + context;

            String result = restTemplate.getForObject(url, String.class);

            log.info("sendSms url is {}, result is {}", url, result);

            count.decrementAndGet();
        }
    }
}
